
public class Modulo implements Expressao {

	private Expressao expr1;
	private Expressao expr2;
	private Integer regFinal;
	
	public Modulo(Expressao expr1, Expressao expr2) {
		super();
		this.expr1 = expr1;
		this.expr2 = expr2;
	}

	@Override
	public String getCode() {
		StringBuffer sb = new StringBuffer();
		regFinal = ParserUtils.novoRegistrador();
		Integer regAux1 = null;
		Integer regAux2 = null;
		
		String s1 = expr1.getCode();
		String s2 = expr2.getCode();
		String modStr = "";
		
		if (expr1 instanceof Literal) {
			modStr = s1 + " mod ";
		} else if (expr1 instanceof Variavel) {
			regAux1 = ParserUtils.novoRegistrador();
			sb.append("ST R" + regAux1 + ", " + s1);
			sb.append(System.lineSeparator());
			modStr = "R" + regAux1 + " mod ";
		} else {
			if (expr1.possuiRegistradorFinal()) {
				regAux1 = ParserUtils.novoRegistrador();
				sb.append(s1);
				sb.append(System.lineSeparator());
				modStr = "R" + regAux1 + " mod ";
			} else {
				modStr = s1 + " mod ";
			}
		}
		
		if (expr2 instanceof Literal) {
			modStr += s2;
		} else if (expr2 instanceof Variavel) {
			regAux2 = ParserUtils.novoRegistrador();
			sb.append("ST R" + regAux2 + ", " + s2);
			sb.append(System.lineSeparator());
			modStr += "R" + regAux2;
		} else {
			if (expr2.possuiRegistradorFinal()) {
				regAux2 = ParserUtils.novoRegistrador();
				sb.append(s2);
				sb.append(System.lineSeparator());
				modStr += "R" + regAux2;
			} else {
				modStr += s2;
			}
		}
		
		sb.append("LD R" + regFinal + ", " + modStr);
		sb.append(System.lineSeparator());
		
		if (regAux1 != null) ParserUtils.liberaRegistradores(regAux1);
		if (regAux2 != null) ParserUtils.liberaRegistradores(regAux2);
		
		return sb.toString();
	}

	@Override
	public Integer registradorFinal() {
		return regFinal;
	}

	@Override
	public boolean possuiRegistradorFinal() {
		return true;
	}

}
